#!/bin/bash

#链接文件
source /etc/profile

#java虚拟机启动参数
JAVA_OPTS=" "

#JAR包路径
APP_NAME="nacos-ez-updown-demo.jar"
#服务暂停后等待时间,默认为120秒
PAUSE_WAIT=15
#进程停止需等待多少秒
SHUTDOWN_WAIT=30

workdir=$(cd $(dirname $0); pwd)

#使用说明，用来提示输入参数
usage() {
    echo "Usage: sh 执行脚本.sh [start|stop|force_stop|restart|force_restart|status|check|pause|resume]"
    exit 1
}

#检查程序是否在运行
checkpid(){
  pid=`ps -ef|grep $APP_NAME|grep -v grep|awk '{print $2}' `
  if [ ! -z "${pid}" ]; then
   return 0 # 0=true
  fi

  return 1 # 1=false
}

#检查程序端口是否已启动
checkport() {
  if checkpid; then
    port=$(netstat -ntlp | grep $pid | awk '{printf $4}' | cut -d':' -f4)
    if [ ! -z "${port}" ]; then
     return 0 # 0=true
    else
      return 1 # 1=false
    fi
  else
    echo "${APP_NAME} is not running!"
    return 1
  fi
}

checktcp() {
  echo "start check connections, $SECONDS."

  if checkport; then
    local count=0;
    until [ `netstat -ntp | grep ESTABLISHED | awk -v port=":$port" '$4~port{print}' | wc -l` = '0' ] || [ ${count} -gt ${PAUSE_WAIT} ]
    do
      if [ `expr ${count} % 5` -eq 0 ]; then
        echo "waiting for connections disconnect!"
      fi
      sleep 1
      let count=$count+1;
    done

    if [ ${count} -gt ${PAUSE_WAIT} ]; then
      echo "wait for ${PAUSE_WAIT} seconds, still have connetion"
      #打印所有的连接
      netstat -ntp | grep ESTABLISHED | awk -v port=":$port" '$4~port{print}'
    fi
  fi
  echo "end check connections, $SECONDS."
}

function check_startup() {
    local timeout=30
    local count=0;
    until [ `netstat -ntlp | grep ${pid} -c` = '1' ] || [ ${count} -gt ${timeout} ]
    do
        echo -n -e "[${count}] Waiting for processes to startup\n"
        sleep 1
        let count=$count+1;
    done
    if [ ${count} -lt ${timeout} ]; then
      return 0
    else
      return 1
    fi
}

# @args <beg> <end>
# return random integer in [<beg>, <end>)
function random_range() {
    local beg=$1
    local end=$2
    echo $((RANDOM % ($end - $beg) + $beg))
}


#启动方法
start(){
  echo "starting ..."

  if checkpid; then
    echo "${APP_NAME} is already running. pid=${pid} ."
  else
    #local port=$(random_range 30000 60000)
    nohup java $JAVA_OPTS -jar $workdir/$APP_NAME  > /dev/null 2>&1 &
    echo "${APP_NAME} starting..."
    sleep 1
    checkpid
    if [ $? -eq "0" ]; then
       check_startup
       checkpid
       if [ $? -eq "0" ]; then
         echo "${APP_NAME} started. pid=${pid}"
       else
         echo "startup failed!"
       fi
    fi
  fi
}

pause() {
  #if checkport; then
    url="http://localhost:8080/actuator/graceful-pause"
    echo $url

    local curlRtn=$(curl --connect-timeout 10 -m 20 -s -XPOST $url | cat)
    echo "service pause $curlRtn"
    sleep 30
  #fi
}

#停止方法
stop(){
  echo "stopping ..."

  if checkpid; then
    #停止分为3个步骤：暂停、检测tcp连接、停止进程
    #pause
    #checktcp
    kill $pid

    local kwait=$SHUTDOWN_WAIT
    local count=0;
    until [ `ps -p $pid | grep -c $pid` = '0' ] || [ $count -gt $kwait ]
    do
      echo "waiting for processes to exit";
      sleep 1
      let count=$count+1;
    done

    if [ $count -gt $kwait ]; then
      echo "killing processes didn't stop after $SHUTDOWN_WAIT seconds"
      kill -9 $pid
    fi

    echo "${APP_NAME} stopped."
  else
    echo "${APP_NAME} is not running"
  fi
}

#快速强制停止
force_stop(){
  echo "stopping ..."

  if checkpid; then

    kill -9 ${pid}

    echo "${APP_NAME} stopped."
  else
    echo "${APP_NAME} is not running"
  fi
}

#输出运行状态
status(){
  if checkpid; then
    echo "${APP_NAME} is running. pid is ${pid}"
  else
    echo "${APP_NAME} is NOT running."
  fi
}

#重启
restart(){
  stop
  start
}

#快速强制重启
force_restart(){
  force_stop
  start
}


#根据输入参数，选择执行对应方法，不输入则执行使用说明
case "$1" in
  "start")
    start
    ;;
  "stop")
    stop
    ;;
  "force_stop")
    force_stop
    ;;
  "status")
    status
    ;;
  "restart")
    restart
    ;;
  "force_restart")
    force_restart
    ;;
  "check")
    checktcp
    ;;
  "pause")
    pause
    ;;
  "resume")
    resume
    ;;
  *)
    usage
    ;;
esac
